package edu.nanyang.controller;

import edu.nanyang.domain.ClassInfo;
import edu.nanyang.domain.PaperInfo;
import edu.nanyang.domain.StudentAnswer;
import edu.nanyang.domain.StudentInfo;
import edu.nanyang.service.ClassInfoService;
import edu.nanyang.service.PaperInfoService;
import edu.nanyang.service.StudentAnswerService;
import edu.nanyang.service.StudentInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/student")

public class StudentAnswerController extends BaseController{
    @Resource
    private StudentAnswerService studentAnswerService;
    @Resource
    private ClassInfoService classInfoService;
    @Resource
    private PaperInfoService paperInfoService;
    @Resource
    private StudentInfoService studentInfoService;

    @PostMapping("/answer")
    public String answer(){
        StudentInfo studentInfo= (StudentInfo) request.getSession().getAttribute("login_student");
        int totalScore=0;
        Map<String,String[]> requestParameterMap=request.getParameterMap();
        for(String key:requestParameterMap.keySet()){
            String[] value=requestParameterMap.get(key);
            if(key.startsWith("answer_")) {
                System.out.println("key=" + key + " value=" + value[0]);
                Integer questionNumId= Integer.valueOf(key.substring(key.indexOf("_")+1,key.length()));
                System.out.println("题号：" + questionNumId + " 学生答案：" + value[0]);

                StudentAnswer studentAnswer=new StudentAnswer();
                studentAnswer.setQuestionNumId(questionNumId);
                studentAnswer.setStudentNumId(studentInfo.getStudentNum());
                studentAnswer.setAnswerType(value[0]);
                PaperInfo paperInfo=paperInfoService.getByQuestionNumId(questionNumId);
                if(paperInfo.getQuestionAnswer().equals(value[0])){
                    studentAnswer.setStudentScore(paperInfo.getQuestionScore());
                    totalScore+=paperInfo.getQuestionScore();
                }else{
                    studentAnswer.setStudentScore(0);
                }
                studentAnswerService.add(studentAnswer);

            }
        }
        List<ClassInfo> classInfoList=classInfoService.findAll();
        int classId=1;
        for(ClassInfo classInfo:classInfoList){
            if(totalScore<=classInfo.getMaxScore() && totalScore>=classInfo.getMinScore()){
                classId=classInfo.getId();
            }
        }
        int result=studentInfoService.updateClass(classId,totalScore,studentInfo.getStudentNum());
        if(result>0){
            request.setAttribute("tip_info","您已答完试卷，确定返回！");
        }
        return "student/index";
    }



}
